package com.education.expenses.eao;

import com.education.expenses.entity.BaseEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;

/**
 * User: alpoloz
 * Date: 7/11/12
 * Time: 6:35 PM
 */
public abstract class HibernateEAO<T extends BaseEntity> implements EAO<T> {

    @Autowired
    private SessionFactory sessionFactory;

    public HibernateEAO(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    protected Criteria createCriteria() {
        return getCurrentSession().createCriteria(getClassOfGenericType());
    }

    //may be not useful hack, but i like it=) Work only with direct inheritance
    private Class getClassOfGenericType() {
        ParameterizedType parameterizedType =
                (ParameterizedType) getClass().getGenericSuperclass();
        return (Class) parameterizedType.getActualTypeArguments()[0];
    }

    @Override
    public T save(T entity) {
        getCurrentSession().save(entity);
//        entity.setId(id);
        return entity;
    }

    @Override
    public void update(T entity) {
        getCurrentSession().update(entity);
    }

    @Override
    public void delete(T entity) {
        getCurrentSession().delete(entity);
    }

    @Override
    public T getById(Long id) {
        Criteria criteria = createCriteria().add(Restrictions.eq("id", id));
        return (T) criteria.uniqueResult();
    }
}